package com.hd.hdxgddcommon.web.wechatUtil;

import com.hd.hdxgddcommon.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;

import static com.hd.hdxgddcommon.web.wechatUtil.RequestSSL.sendHttps;


@Slf4j
public class WechatUtils {


    /**
     * 获取openID等信息
     */
    public static Map<String, Object> getOpenId(String code, String APPID, String APP_SECRET) {

        String url = WechatConstant.OPENID_JSCODE_SUFFIX;
        url = url.replace("{APPID}", APPID).replace("{SECRET}", APP_SECRET).replace("{CODE}", code);
        try {
            String result = sendHttps(url, "get", null);
            if (!result.contains("errcode")) {
                return JsonUtil.JsonStrToMap(result);
            } else {
                log.error(result);
            }
        } catch (Exception e) {
            log.error("获取openId异常", e);
            return null;
        }
        return null;
    }


    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     */
    public static String getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.getDecoder().decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.getDecoder().decode(iv);
        try {

            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                return new String(resultByte, "UTF-8");
            }
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidParameterSpecException | BadPaddingException
                | IllegalBlockSizeException | InvalidKeyException e) {
            log.error("数据金额加密异常", e);
        } catch (UnsupportedEncodingException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }


//    /**
//     * 获取access_token等信息
//     */
//    public static String getAccessToken(String APPID, String APP_SECRET) {
//
//        String url = WXPayConstants.GET_ACCESS_TOKEN_SUFFIX;
//        url = url.replace("{APPID}", APPID).replace("{SECRET}", APP_SECRET);
//        String result = null;
//        try {
//            result = sendHttps(url, "get", null);
//        } catch (Exception e) {
//            log.error("获取accessToken异常", e);
//            result = null;
//        }
//        return result;
//    }

//    public static void main(String[] args) {
////        String encryptedData = "H2p0OXBZa4OjHIPVN0F6GKhcwPciRLkBPPVX9XIvCdu1TKBxNKWNIZ0zQSAohtzWuiG3GVY+/A027JDRgRrlQDSRNbLxCFjHGDAeM+45VwAbDdY5fOmly5xY6TSCVaiX0IFz2amL8JQNophLczxJ1y5oxXuvNKXHefRH81Zc9qeo+OtVjCWQ/VEgTtK0Dzo8ScjyRi6XnbpA6yySLzOjgLB8JuSD4VCZu5iwnLj/1yzR0jDqca5FTcrI/uRdl1AThIyfEXBaRnq2WKd2+DPgZclrz0QiSnUZ2JvaySG2jMTPsgLqflMBJXuJY2NESSZubWCZN3aV++oKZDj1JMWBaj1Qkc2zuN55NYgx2DwtupHO+EtzYpMH5MH6qG60HW8P837qmmtVDLcwAKJJwrMF2SBq3ctSMiRlQJZhBcwSB8hQEc48JZduZn7m9qBbNzn3gzngPWZzNsJ7xUk4xRyKtZtlAOZsZ3GZLC/LG//JsOw=";
////        String iv = "CIyMrjzlQ688BCyZs12ekw==";
////        String se = "fyEpmmy2bN0jAGpSDhsOyg==";
////        System.out.println(getOpenId("07180DZ01a38wY1SHpY01CtpZ0180DZI"));
////        System.out.println(SESSION_KEY);
////        System.out.println(SESSION_KEY.get("ooh9d5UiLRnpQ6f-4gCXJPgTv3go"));
////        System.out.println(getAccessToken());
////        Map<String,Object> map = JsonUtil.JsonStrToMap(getAccessToken());
////        System.out.println(JsonUtil.JsonStrToMap(getAccessToken()));
////        System.out.println(map.get("access_token"));
////        System.out.println(getUserInfo(encryptedData,se,iv));
//          System.out.println(UUID.randomUUID().toString().substring(0,8));
//          String as = "21_BoLqBsOySiNxKhOKNyw0TW97MK5EBtQaWacaqoS_pxLP0Mc6zUgPYVuaaoWtOLopypweFxDJepYPQ0V6vNXtTIYB86AtvkpHMLeHpRM6rmCmJhPYHS58ECU0AVoLg9xnb1sIG-ZPCzUoCw6fIJKfAGADEF";
//          JSONObject jsonObject = new JSONObject();
//          jsonObject.put("path","pages/testList/testList?fieldId="+23);
//          System.out.println( getWxACode(jsonObject.toJSONString(),as));
//    }

}
